class RecordsController < ApplicationController
  before_action :set_record, only: [:show, :edit, :update, :destroy]
  
  respond_to :html,:js

  def index
    @records = Record.all
    respond_with(@records)
  end

  def show
    respond_with(@record)
  end

  def entry
    if params[:entry_type].present? and params[:entry_source].present?
      @entry_id = params[:entry_id]
      @entry_type = params[:entry_type]
      if @entry_type == "income"
        @selected_source = Income.find(params[:entry_source])
      elsif @entry_type == "expense"
        @selected_source = Expense.find(params[:entry_source])
      end
    end
  end

  def new
    if params[:entry_type].present?
      @entry_type = params[:entry_type]
    end
    @income = Income.all
    @expense  = Expense.all
    @record = Record.new
    @record.entries.build
    respond_with(@record)
  end

  def edit
  end

  def create
    @record = Record.new(record_params)
    @record.account = @profile.accounts.find_by_name('Asset')
    @record.save
    respond_with(@record)
  end

  def update
    @record.update(record_params)
    respond_with(@record)
  end

  def destroy
    @record.destroy
    respond_with(@record)
  end

  private
    def set_record
      @record = Record.find(params[:id])
    end

    def record_params
      params.require(:record).permit(:name, entries_attributes: 
        [:id, :record_id, :income_id, :expense_id, :trans_date, :trans_type, :description, :level, :duration, :amount, :_destroy])
    end
end
